<?php

/**
 * facturaconsumo actions.
 *
 * @package    sf_sandbox
 * @subpackage facturaconsumo
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class facturaconsumoActions extends sfActions {

    /**
     * Executes index action
     *
     * @param sfRequest $request A request object
     */
    public function executeIndex(sfWebRequest $request) {
        $this->forward404Unless($this->unidad_funcional = Doctrine_Core::getTable('UnidadFuncional')->find(array("2")), sprintf('Object unidad_funcional does not exist (%s).', "1"));
    }

    public function executeFiltro(sfWebRequest $request) {
        $idTipoComprobante = TipoComprobanteTable::getId("FC");
        $this->getUser()->setAttribute("idTipoComprobante", $idTipoComprobante);
        $this->getUser()->setAttribute("itemsconceptos", Array());
        $comprobante = ComprobanteTable::getUltimo();
        'cargo el periodo que se va a facturar';
        $this->periodo = PeriodoTable::getBuscarPeriodoAbierto(true);
        $this->getUser()->setAttribute("periodoAfacturar", $this->periodo);
        if (count($comprobante) > 0) {
            $this->nrocomprobante = $comprobante['nro_comprobante'] + 1;
        } else {
            $this->nrocomprobante = 1;
        }
        $this->getUser()->setAttribute("nrocomprobante", $this->nrocomprobante);
    }

    public function executeBuscar(sfWebRequest $request) {
        $this->setLayout("busqueda");
    }

    public function executeBuscarConceptos(sfWebRequest $request) {
        $this->setLayout("busqueda");
    }

    protected function getPager($q, $page, $model) {
        $pager = new sfDoctrinePager($model, sfConfig::get('app_nro_x_pagina_contribuyente'));
        $pager->setQuery($q);
        $pager->setPage($page);
        $pager->init();

        return $pager;
    }

    public function executeFiltrarConceptos(sfWebRequest $request) {

        if ($request->isMethod('post')) {
            $nombre = $request->getPostParameter("nombre");
        } else {
            $nombre = $request->getGetParameter("nombre");
        }
        $this->conceptos = $this->getPager(ConceptoTable::getBuscarConceptos($nombre), $request->getGetParameter('page'), "Concepto");
        if ($request->isXmlHttpRequest()) {
            return $this->renderPartial("facturaordinaria/listadoconceptos", array('conceptos' => $this->conceptos));
        }
    }

    public function executeExistecomprobante(sfWebRequest $request) {
        $id = $this->getUser()->getAttribute("idLectura");
        if ($id != 0) {
            $existeComprobante = ComprobanteTable::getExisteComprobanteLectura($id);
            if ($existeComprobante == 1) {
                $array[0]['existe'] = $existeComprobante;
            } else {
                $array[0]['existe'] = $existeComprobante;
            }
        } else {
            $array[0]['existe'] = 1;
        }
        $array[0]['lectura'] = $id;
        return $this->renderText(json_encode($array));
    }

    public function executeBuscarlectura(sfWebRequest $request) {
        $iduf = $request->getPostParameter("id");
        $this->getUser()->setAttribute("iduf", $iduf);
        $lectura = LecturaTable::getUltimaLectura2($iduf);

        if (count($lectura) > 0) {
            $this->idLec = $lectura[0]['lecturaid'];
            $existeComprobante = ComprobanteTable::getExisteComprobanteLectura($lectura[0]['lecturaid']);
            $this->getUser()->setAttribute("idLectura", $lectura[0]['lecturaid']);
            //echo $existeComprobante." aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            if ($existeComprobante == 1) {
                $this->lectura = Array();
                //$this->getUser()->setAttribute("idLectura", 0);
                $this->idLec = "0";
                $this->getUser()->setAttribute("existeComprobante", $existeComprobante);
            } else {
                $this->lectura = $lectura;
                $this->getUser()->setAttribute("existeComprobante", $existeComprobante);
            }
        } else {
            $this->lectura = Array();
            $this->getUser()->setAttribute("idLectura", 0);
            $this->idLec = "1";
        }
    }

    public function executeBuscarconceptosfijos(sfWebRequest $request) {

        $this->conceptos = ConceptoTable::getBuscarConceptosFijos();
        $this->getUser()->setAttribute("conceptosfijos", $this->conceptos);
    }

    public function executeFiltrarUnidadesFuncionales(sfWebRequest $request) {
        if ($request->isMethod('post')) {
            $dato = $request->getPostParameter("dato");
        } else {
            $dato = $request->getGetParameter("dato");
        }

        $this->unidadesFuncionales = $this->getPager(UnidadFuncionalTable::getBuscarUnidadesPopUp($dato), $request->getGetParameter('page'), "UnidadFuncional");
        if ($request->isXmlHttpRequest()) {
            return $this->renderPartial("facturaconsumo/resultadoUnidadesFuncionales", array('unidadesFuncionales' => $this->unidadesFuncionales));
        }
    }

    public function executeAgregar(sfWebRequest $request) {
        $itemsconceptos = $this->getUser()->getAttribute("itemsconceptos");
        $id = $request->getGetParameter("id");
        $concepto = Doctrine_Core::getTable('Concepto')->find(array($request->getParameter('id')));
        $itemsconceptos[$id]['iduf'] = $request->getGetParameter("iduf");
        $itemsconceptos[$id]['id'] = $id;
        $itemsconceptos[$id]['codigo'] = $concepto->getCodigo();
        $itemsconceptos[$id]['nombre'] = $concepto->getNombre();
        $itemsconceptos[$id]['precio'] = $request->getParameter("precio");
        $itemsconceptos[$id]['cuenta'] = $concepto->getCuenta();

        $this->getUser()->setAttribute("itemsconceptos", $itemsconceptos);
        return $this->renderPartial("facturaordinaria/itemsconceptos", array('itemsconceptos' => $itemsconceptos));
    }

    public function executeEliminar(sfWebRequest $request) {
        $pos = $request->getParameter("id");
        $itemsconceptos = $this->getUser()->getAttribute("itemsconceptos");
        unset($itemsconceptos[$pos]);
        $this->getUser()->setAttribute("itemsconceptos", $itemsconceptos);
        return $this->renderPartial("facturaordinaria/itemsconceptos", array('itemsconceptos' => $itemsconceptos));
    }

    public function executeImprimir(sfWebRequest $request) {
        $itemsconceptos = $this->getUser()->getAttribute("itemsconceptos");
        $nro_comprobante = $this->getUser()->getAttribute("nrocomprobante");
        foreach ($itemsconceptos as $i => $item) {
            $iduf = $item['iduf'];
        }
        $this->guardarFactura($itemsconceptos, $nro_comprobante, $iduf);
        $unidad_funcional = Doctrine_Core::getTable('UnidadFuncional')->find(array($iduf));
        $html = $this->getPartial('facturaordinaria/imprimir', array('unidadfuncional' => $unidad_funcional, 'conceptos' => $itemsconceptos));

        $config = sfTCPDFPluginConfigHandler::loadConfig();

        // pdf object
        $pdf = new sfTCPDF();

        // set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('NORDSOFT');
        //$pdf->SetTitle('Planilla Relevamiento de Lecturas');
        // set default header data
        $pdf->SetHeaderData("", "", PDF_HEADER_TITLE, "Servicio de administración y provisión de agua potable");

        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

        // set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        //set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, 20, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        //set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

        //set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        // ---------------------------------------------------------
        // set default font subsetting mode
        $pdf->setFontSubsetting(true);

        // Set font
        // dejavusans is a UTF-8 Unicode font, if you only need to
        // print standard ASCII chars, you can use core fonts like
        // helvetica or times to reduce file size.
        $pdf->SetFont('dejavusans', '', 14, '', true);

        // Add a page
        // This method has several options, check the source code documentation for more information.
        $pdf->AddPage();

        // Set some content to print
        // Print text using writeHTMLCell()
        $pdf->writeHTMLCell($w = 0, $h = 0, $x = '', $y = '', $html, $border = 0, $ln = 1, $fill = 0, $reseth = true, $align = '', $autopadding = true);

        // ---------------------------------------------------------
        // Close and output PDF document
        // This method has several options, check the source code documentation for more information.
        $pdf->Output('example_001.pdf', 'I');

        // Stop symfony process
        throw new sfStopException();
    }

    private function guardarFactura($itemsconceptos, $nro_comprobante, $iduf,$totalfinal) {
        $periodo = $this->getUser()->getAttribute("periodoAfacturar");
        $fc = new Comprobante();
        $fc->setCategoriaAguaId(1);
        $fc->setFechaEmision(date("Y-m-d h:i:s"));
        $fc->setImporteCuota($totalfinal);
        $fc->setNroComprobante($nro_comprobante);
        $fc->setUnidadFuncionalId($iduf);
        $fc->setTipoComprobanteId($this->getUser()->getAttribute("idTipoComprobante"));
        $idLectura = $this->getUser()->getAttribute("idLectura");
        $fc->setLecturaId($idLectura);
        $fc->setPeriodoId($periodo->getId());
        $fc->save();

        //recorro cada uno de los conceptos para ir agregando a la linea comprobante  
        //Concetpos fijos
        $fijos = $this->getUser()->getAttribute("conceptosfijos");
        foreach ($fijos as $i => $item) {
            $fcl = new LineaComprobante();
            $fcl->setComprobanteId($fc->getId());
            $fcl->setValor($item['valor']);
            $fcl->setConceptoId($item['id']);
            $fcl->save();
        }
        //conceptos variables
        foreach ($itemsconceptos as $i => $item) {
            $fcl = new LineaComprobante();
            $fcl->setComprobanteId($fc->getId());
            $fcl->setValor($item['precio']);
            $fcl->setConceptoId($item['id']);
            $fcl->save();
        }
        //registro el pago despues de haber guardado la factura 
//        $pago = new Pago();
//        $pago->setFormaPagoId(1);
//        $pago->setFechahora(date('Y-m-d H:i:s'));
//        $pago->save();
//        $pago_linea = new PagoLinea();
//        $pago_linea->setPagoId($pago->getId());
//        $pago_linea->setComprobanteId($fo->getId());
//        $pago_linea->setMora(0);
//        $pago_linea->save();
        return $fc->getNroComprobante();
    }

    public function executeCrearfactura(sfWebRequest $request) {

        $itemsconceptos = $this->getUser()->getAttribute("itemsconceptos"); //conceptosvariables
        $conceptosfijos = $this->getUser()->getAttribute("conceptosfijos");
        $nro_comprobante = $this->getUser()->getAttribute("nrocomprobante");
        $iduf = $this->getUser()->getAttribute("iduf");
        $lectura = LecturaTable::getUltimaLecturaReporte($iduf);
        $unidad_funcional = Doctrine_Core::getTable('UnidadFuncional')->find(array($iduf));
        //calculo el total
        $totalfijos = 0;
         $total = 0;
         $totallectura = 0;
        foreach ($conceptosfijos as $i => $c):
            $totalfijos += $c['valor'];
        endforeach;
        $total = 0;
        foreach ($itemsconceptos as $i => $c):
            $total += $c['precio'];
        endforeach;
        foreach ($lectura as $j => $l):
            $lant = $l['lectura_anterior'];
            $lact = $l['lectura_actual'];
            $valormts3 = $unidad_funcional->getCategoriaAgua()->getValor();
            $totallectura = (($lact - $lant) * $valormts3);
        endforeach;
        //suma de todos los conceptos y lectura  
        
//        $totalfinal = $total+$totalfijos+ $totallectura;
        
         try {
              $nrofo = $this->guardarFactura($itemsconceptos, $nro_comprobante, $iduf,$valormts3);
//            $nrofo = $this->guardarFactura($itemsconceptos, $nro_comprobante, $iduf,$totalfinal);
            // $nrofo = 0;
            $this->getUser()->setFlash('notice', "La factura se registró con el número: " . $nrofo);
        } catch (Exception $e) {
            $this->getUser()->setFlash('error', $e->getMessage());
        }
        
        $html = $this->getPartial('facturaconsumo/factura', array('unidadfuncional' => $unidad_funcional, 'conceptos' => $itemsconceptos, 'lectura' => $lectura, 'conceptosfijos' => $conceptosfijos));

        $config = sfTCPDFPluginConfigHandler::loadConfig();

        // pdf object
        $pdf = new sfTCPDF();

        // set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('NORDSOFT');
        //$pdf->SetTitle('Planilla Relevamiento de Lecturas');
        // set default header data
        $pdf->SetHeaderData("", "", PDF_HEADER_TITLE, "Servicio de administración y provisión de agua potable");

        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
        // set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        //set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, 25, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        //set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

        //set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        // ---------------------------------------------------------
        // set default font subsetting mode
        $pdf->setFontSubsetting(true);

        // Set font
        // dejavusans is a UTF-8 Unicode font, if you only need to
        // print standard ASCII chars, you can use core fonts like
        // helvetica or times to reduce file size.
        $pdf->SetFont('dejavusans', '', 14, '', true);

        // Add a page
        // This method has several options, check the source code documentation for more information.
        $pdf->AddPage();

        // Set some content to print
        // Print text using writeHTMLCell()
        $pdf->writeHTMLCell($w = 0, $h = 0, $x = '', $y = '', $html, $border = 0, $ln = 1, $fill = 0, $reseth = true, $align = '', $autopadding = true);

        // ---------------------------------------------------------
        // Close and output PDF document
        // This method has several options, check the source code documentation for more information.
        $pdf->Output('example_001.pdf', 'I');

        // Stop symfony process

        throw new sfStopException();
       
    }

}

